{% extends 'migration_app/base.html' %}

{% block content %}
<div class="row mb-4">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="card-title mb-0">
                    <i class="fas fa-exchange-alt me-2"></i>数据迁移
                </h5>
            </div>
            <div class="card-body">
                <form id="migration-form">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="task-name" class="form-label">任务名称</label>
                            <input type="text" class="form-control" id="task-name" required>
                        </div>
                        <div class="col-md-6">
                            <label for="task-type" class="form-label">迁移类型</label>
                            <select class="form-select" id="task-type" required>
                                <option value="" selected disabled>请选择迁移类型</option>
                                <option value="table">表</option>
                                <option value="all_tables">所有表</option>
                                <option value="materialized_view">物化视图</option>
                                <option value="view">视图</option>
                                <option value="routine">例程</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="oracle-connection" class="form-label">Oracle连接</label>
                            <select class="form-select" id="oracle-connection" required>
                                <option value="" selected disabled>请选择Oracle连接</option>
                                {% for conn in oracle_connections %}
                                <option value="{{ conn.id }}">{{ conn.name }} ({{ conn.host }}:{{ conn.port }})</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="postgres-connection" class="form-label">PostgreSQL连接</label>
                            <select class="form-select" id="postgres-connection" required>
                                <option value="" selected disabled>请选择PostgreSQL连接</option>
                                {% for conn in postgres_connections %}
                                <option value="{{ conn.id }}">{{ conn.name }} ({{ conn.host }}:{{ conn.port }})</option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label for="source-schema" class="form-label">源Schema</label>
                            <select class="form-select" id="source-schema" required>
                                <option value="" selected disabled>请选择Schema</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="target-schema" class="form-label">目标Schema</label>
                            <input type="text" class="form-control" id="target-schema" required>
                        </div>
                        <div class="col-md-4">
                            <label for="source-object" class="form-label">源对象名称</label>
                            <select class="form-select" id="source-object" required>
                                <option value="" selected disabled>请选择对象</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="text-end">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-play me-1"></i>开始迁移
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="card-title mb-0">
                    <i class="fas fa-history me-2"></i>最近任务
                </h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>任务名称</th>
                                <th>类型</th>
                                <th>源对象</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="tasks-table">
                            {% for task in tasks %}
                            <tr>
                                <td>{{ task.name }}</td>
                                <td>{{ task.get_task_type_display }}</td>
                                <td>{{ task.source_schema }}.{{ task.source_object }}</td>
                                <td>
                                    {% if task.status == 'pending' %}
                                    <span class="badge bg-warning">待执行</span>
                                    {% elif task.status == 'running' %}
                                    <span class="badge bg-info">执行中</span>
                                    {% elif task.status == 'completed' %}
                                    <span class="badge bg-success">已完成</span>
                                    {% elif task.status == 'failed' %}
                                    <span class="badge bg-danger">失败</span>
                                    {% endif %}
                                </td>
                                <td>{{ task.created_at|date:"Y年m月d日 H:i:s" }}</td>
                                <td>
                                    <a href="{% url 'migration_app:task_detail' task.id %}" class="btn btn-sm btn-primary">
                                        <i class="fas fa-eye"></i> 查看
                                    </a>
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="6" class="text-center">暂无任务记录</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('migration-form');
        const taskTypeSelect = document.getElementById('task-type');
        const sourceObjectSelect = document.getElementById('source-object');
        const sourceObjectLabel = document.querySelector('label[for="source-object"]');
        const oracleConnectionSelect = document.getElementById('oracle-connection');
        const sourceSchemaSelect = document.getElementById('source-schema');
        
        // 初始化状态
        updateSourceObjectField();
        
        // 添加事件监听器
        taskTypeSelect.addEventListener('change', function() {
            updateSourceObjectField();
            if (sourceSchemaSelect.value && taskTypeSelect.value !== 'all_tables') {
                fetchDatabaseObjects();
            }
        });
        
        oracleConnectionSelect.addEventListener('change', function() {
            if (oracleConnectionSelect.value) {
                fetchSchemas();
            }
        });
        
        sourceSchemaSelect.addEventListener('change', function() {
            if (sourceSchemaSelect.value && taskTypeSelect.value !== 'all_tables') {
                fetchDatabaseObjects();
            }
        });
        
        function updateSourceObjectField() {
            const selectedType = taskTypeSelect.value;
            
            if (selectedType === 'all_tables') {
                sourceObjectSelect.required = false;
                sourceObjectSelect.value = '';
                sourceObjectSelect.disabled = true;
                sourceObjectLabel.parentElement.style.display = 'none';
            } else {
                sourceObjectSelect.required = true;
                sourceObjectSelect.disabled = false;
                sourceObjectLabel.parentElement.style.display = 'block';
            }
        }
        
        function fetchSchemas() {
            const connectionId = oracleConnectionSelect.value;
            if (!connectionId) return;
            
            // 清空现有选项
            sourceSchemaSelect.innerHTML = '<option value="" selected disabled>加载中...</option>';
            
            fetch('{% url "migration_app:get_schemas" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    connection_id: connectionId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 清空选项并添加默认选项
                    sourceSchemaSelect.innerHTML = '<option value="" selected disabled>请选择Schema</option>';
                    
                    // 添加获取到的Schema
                    data.schemas.forEach(schema => {
                        const option = document.createElement('option');
                        option.value = schema;
                        option.textContent = schema;
                        sourceSchemaSelect.appendChild(option);
                    });
                } else {
                    alert('获取Schema失败: ' + data.message);
                    sourceSchemaSelect.innerHTML = '<option value="" selected disabled>请选择Schema</option>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生错误，请检查控制台');
                sourceSchemaSelect.innerHTML = '<option value="" selected disabled>请选择Schema</option>';
            });
        }
        
        function fetchDatabaseObjects() {
            const connectionId = oracleConnectionSelect.value;
            const schema = sourceSchemaSelect.value;
            const objectType = taskTypeSelect.value;
            
            if (!connectionId || !schema || !objectType || objectType === 'all_tables') return;
            
            // 清空现有选项
            sourceObjectSelect.innerHTML = '<option value="" selected disabled>加载中...</option>';
            
            fetch('{% url "migration_app:get_database_objects" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    connection_id: connectionId,
                    schema: schema,
                    object_type: objectType
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 清空选项并添加默认选项
                    sourceObjectSelect.innerHTML = '<option value="" selected disabled>请选择对象</option>';
                    
                    // 添加获取到的对象
                    data.objects.forEach(obj => {
                        const option = document.createElement('option');
                        option.value = obj;
                        option.textContent = obj;
                        sourceObjectSelect.appendChild(option);
                    });
                    
                    if (data.objects.length === 0) {
                        sourceObjectSelect.innerHTML = '<option value="" selected disabled>未找到对象</option>';
                    }
                } else {
                    alert('获取对象失败: ' + data.message);
                    sourceObjectSelect.innerHTML = '<option value="" selected disabled>请选择对象</option>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生错误，请检查控制台');
                sourceObjectSelect.innerHTML = '<option value="" selected disabled>请选择对象</option>';
            });
        }
        
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const taskData = {
                name: document.getElementById('task-name').value,
                task_type: taskTypeSelect.value,
                oracle_connection: oracleConnectionSelect.value,
                postgres_connection: document.getElementById('postgres-connection').value,
                source_schema: sourceSchemaSelect.value,
                target_schema: document.getElementById('target-schema').value,
                source_object: sourceObjectSelect.value
            };
            
            fetch('{% url "migration_app:create_task" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(taskData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert('任务创建成功!');
                    window.location.href = `{% url "migration_app:task_detail" 0 %}`.replace('0', data.task_id);
                } else {
                    alert('错误: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生错误，请检查控制台');
            });
        });
    });
</script>
{% endblock %} 